package com.njupt.watcherdemo;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;


/**
 * Created by caolicheng on 15/3/30.
 * 广播接收器
 */
public class WatcherReceiver extends BroadcastReceiver {
    private final static String TAG = "watcher";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "触发广播：" + intent.getAction());
        if (!isServiceRunning(context)) {
            Log.e(TAG, "监控的Service已经死掉！");
            context.startService(new Intent(context, DemoService.class));
        }
    }

    private boolean isServiceRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.njupt.watcherdemo.DemoService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}
